import { dayjs } from 'element-plus'

class Watermark {
  constructor(options = {}) {
    this.options = Object.assign(
      {},
      {
        id: 'mask_vm_id',
        text: '测试水印',
        width: 400,
        height: 200,
        fontSize: 16,
        color: '#000',
        alpha: 0.15, // 水印透明度，要求设置在大于等于0.005
        parentNode: null,
        monitor: true // monitor 是否监控， true: 不可删除水印; false: 可删水印。
      },
      options
    )
    this.init()
  }
  init() {
    this.mutationObserver()
    this.applyWatermark()
  }
  mutationObserver() {
    const MutationObserver =
      window.MutationObserver ||
      window.WebKitMutationObserver ||
      window.MozMutationObserver
    this.watermarkDom = new MutationObserver(mutations => {
      this.domChangeCallback(mutations)
    })
    this.hasObserver = MutationObserver !== undefined
  }
  // 监听父节点的尺寸是否发生了变化, 如果发生改变, 则进行重新绘制
  domChangeCallback(mutations) {
    if (
      (this.options && mutations.length === 1) ||
      (mutations.length === 1 && mutations[0].removedNodes.length >= 1)
    ) {
      this.applyWatermark()
    }
  }
  applyWatermark() {
    //如果元素存在则移除
    const el = document.getElementById(this.options.id)
    el && el.parentNode && el.parentNode.removeChild(el)
    //创建水印区域
    const _parentEle = document.getElementById(this.options.parentNode)
    const parentEle = _parentEle || document.body
    const watermarkUrl = this.generateWatermark()
    const watermarkLayer = document.createElement('div')
    watermarkLayer.id = this.options.id
    watermarkLayer.style.cssText = `
        position: absolute;
        top: 0;
        left: 0;
        z-index:99999;
        opacity:${this.options.alpha};
        width:100%;
        height: 100%;
        background-image: url(${watermarkUrl});
        background-repeat: repeat;
        pointer-events: none;
    `
    parentEle.style.position = 'relative' // 应用样式
    parentEle.appendChild(watermarkLayer) // 将水印层添加到元素中

    // monitor 是否监控， true: 不可删除水印; false: 可删水印。
    const minotor = this.options.monitor
    const observeConfig = {
      childList: true,
      attributes: true,
      subtree: true,
      attributeFilter: ['style'],
      attributeOldValue: true
    }
    if (minotor && this.hasObserver) {
      this.watermarkDom.observe(parentEle, observeConfig)
      this.watermarkDom.observe(
        document.getElementById(this.options.id),
        observeConfig
      )
    }
  }
  generateWatermark() {
    const canvas = document.createElement('canvas') // 创建canvas元素
    canvas.width = this.options.width // 设置canvas宽度
    canvas.height = this.options.height // 设置canvas高度
    const ctx = canvas.getContext('2d') // 获取2D绘图上下文
    ctx.font = `${this.options.fontSize}px Arial` // 设置字体大小和字体样式
    ctx.fillStyle = this.options.color // 设置字体颜色
    ctx.translate(20, canvas.height - 20) // 平移坐标原点
    ctx.rotate(-Math.PI / 6) // 旋转角度
    const currentTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    const watermarkText = this.options.text
      ? `${this.options.text} ${currentTime}`
      : `Watermark ${currentTime}`
    ctx.fillText(watermarkText, 0, 0) // 绘制文本
    return canvas.toDataURL('image/png') // 将canvas内容转换为base64格式的图片
  }
  //移除水印
  removeMark() {
    const el = document.getElementById(this.options.id)
    const _parentEle = el.parentNode
    _parentEle.removeChild(el)
    this.watermarkDom.disconnect()
  }
}

export default Watermark
